package com;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class WWWSocket{
	String server;
	int port;
	String code;
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Date dt = new Date();
	boolean isClosed=false;
	
	public WWWSocket(String server, int port, String code) {
		this.server = server;
		this.port = port;
		this.code = code;
	}

	Socket socket;
	

	public boolean IsClose() {
		if (isClosed) {
			close();
		}
		return isClosed;
	}

	public void start() throws IOException, InterruptedException {
		System.out.println(sdf.format(new Date()) + " WWWSocket start");
		dt = new Date();
		new Thread(new Runnable() {

			public void run() {
				try {
					socket = new Socket(server, port);
					OutputStream os = socket.getOutputStream();
					SocketHelper.writeByte(os, (byte) 0);
					SocketHelper.writeStr(os, code);
					InputStream is = socket.getInputStream();
					int clentcode = SocketHelper.readInt(is, 5000);
					System.out.println("clentcode:" + clentcode);
					
					new Thread(new Runnable() {
						
						@Override
						public void run() {
							try {
								InputStream is = socket.getInputStream();
								OutputStream os = socket.getOutputStream();
								while (true) {
									int flag = SocketHelper.readByte(is, 0);
									dt = new Date();
									if (flag == 1) {
										String data = SocketHelper.readStr(is, 0);
										if (data != null) {
											data = Aes.Decrypt(data, Main.txmy);
											MsgObj obj = MsgObj.fromJson(data);
											String resmsg = "";
											if (!obj.getType().equals("3")
													&& !obj.getType().equals("4")) {
												resmsg = "1";
												MsgHandler.sendMsg(obj);
											} else if (obj.getType().equals(4)) {
												resmsg = "1";
											} else {
												String theurl = Main.getUrl();
												resmsg = theurl == null ? "0" : theurl;
											}
											SocketHelper.writeStr(os, resmsg);
										} else {
											break;
										}
									} else {
										SocketHelper.writeByte(os, (byte) 1);
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
							isClosed = true;
							System.out.println(sdf.format(new Date()) + " WWWSocket stop2");
						}
					}).start();
					
					
					while ((new Date()).getTime() - dt.getTime() < 30000) {
						Thread.sleep(15000);
					}
					socket.close();
				} catch (Exception e) {
				}
				System.out.println(sdf.format(new Date()) + " WWWSocket stop1");
				isClosed = true;
			}
		}).start();

	}

	public void close() {
		try {
			socket.close();
		} catch (Exception e) {
		}
		System.out.println(sdf.format(new Date()) + " WWWSocket close");
	}
}
